// Reflect和Proxy对象一样，ES6操作对象而提供的心的API

// 1.Reflect对象可以拿到对象内部的方法，未来的新方法也只将部署到Reflect上
// 2.

let user = {
  name: 'dd',
  age: 20,
  get remark() {
    return this.name + this.age
  }
}

try {
  Object.defineProperty(user, 'name', { value: 'ldd' })
} catch (e) {
  console.log('Object---', e);
}

console.log(user);

if (Reflect.defineProperty(user, 'age', { value: 18 })) {
  console.log('Reflect--Success')
} else {
  console.log('Reflect--Error')
}
console.log(user);

// 3.让Object操作都变成函数行为

console.log('name' in user);

console.log(Reflect.has(user, 'name'))


// 4. Reflect对象的方法与Proxy对象的方法一一对应

new Proxy(user, {
  get(target, key, receiver) {
    return Reflect.get(target, key, receiver)
  },
  set(target, key, value, receiver) {
    return Reflect.set(target, key, value, receiver)
  },
  has(target, key) {
    return Reflect.has(target, key)
  },
  deleteProperty(target, key) {
    return Reflect.deleteProperty(target, key)
  }
})


// 静态方法

console.log('Reflect.get---', Reflect.get(user, 'name'));

let user1 = {
  name: 'liudandan',
  age: 25
}
// 如果属性设置了getter,则读取函数的this绑定receiver
console.log('Reflect.get---', Reflect.get(user, 'remark', user1));


console.log("Reflect.set---", Reflect.set(user, 'sex', 'girls'), user);
// 如果Proxy对象与Reflect一起使用，前者拦截赋值后者赋值，而且传入receiver时，Reflect.set会触发proxy.defineProperty拦截



let student = {
  set(target, key, value, receiver) {
    Reflect.set(target, key, value, receiver)
  },
  defineProperty(target, key, attribute) {
    console.log('receiver触发了obj的defineProperty拦截---');
    Reflect.defineProperty(target, key, attribute)
  }
}

let San = new Proxy({}, student)
San.name = 'San'


console.log("Reflect.has--", Reflect.has(user, 'sex'));

console.log("Reflect.deleteProperty--", Reflect.deleteProperty(user, 'remark'));

console.log("Reflect.construct---", Reflect.construct(function (str) { this.text = str }, ['text']));

console.log("reflect.getPrototypeOf----", Reflect.getPrototypeOf(user));

console.log("Reflect.setPrototypeOf----", Reflect.setPrototypeOf(user, Array.prototype));

console.log("Reflect.apply----");

console.log("Reflect.getOwnPropertyDescriptor---");
console.log("Reflect.isExtensible---");
console.log("Reflect.preventExtensions---");


console.log("Reflect.ownkeys---", Reflect.ownKeys(user));


console.log('使用Proxy实现观察者模式');



const observeable = obj => new Proxy(obj, {
  set(target, key, value, receiver) {
    queuedObservers.forEach(observe => observe())
    return Reflect.set(target.key, value, receiver)
  }
})

// 观察目标
const person = observeable({
  name: 'ldd',
  age: 20
})


// 观察者
function print() {
  console.log(`${person.name},${person.age}`);
}

// 观察者对象集合
const queuedObservers = new Set()

const observe = fn => queuedObservers.add(fn)
// 添加观察者
observe(print)






